import { Inject, Injectable, forwardRef } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { DelFlagEnum, StatusEnum } from 'src/common/enum'
import { Uniq } from 'src/common/utils'
import { In, Repository } from 'typeorm'
import { SysRoleWithMenuEntity } from '../role/entities/role-width-menu.entity'
import { UserService } from '../user/user.service'
import { SysMenuEntity } from './entities/menu.entity'
import { buildMenus } from './utils'

@Injectable()
export class MenuService {
  constructor(
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    @InjectRepository(SysMenuEntity)
    private readonly sysMenuEntityRep: Repository<SysMenuEntity>,
    @InjectRepository(SysRoleWithMenuEntity)
    private readonly sysRoleWithMenuEntityRep: Repository<SysRoleWithMenuEntity>
  ) {}
  /**
   * 根据用户id， 获取用户的菜单信息
   * @param userId 用户ID
   * @return 菜单列表
   */
  async getMenuListByUserId(userId: number) {
    let menuWidthRoleList = []
    const roleIds = await this.userService.getRoleIds([userId])
    // 超管 roleId = 1 获取所有菜单权限
    if (roleIds.includes(1)) {
      menuWidthRoleList = await this.sysMenuEntityRep.find({
        where: {
          delFlag: DelFlagEnum.NORMAL,
          status: StatusEnum.NORMAL
        },
        select: ['menuId']
      })
    } else {
      // 查询角色绑定的菜单
      menuWidthRoleList = await this.sysRoleWithMenuEntityRep.find({
        where: { roleId: In(roleIds) },
        select: ['menuId']
      })
    }
    // 菜单id 去重
    const menuIds = Uniq(menuWidthRoleList.map((item) => item.menuId))
    // 菜单列表
    const menuList = await this.sysMenuEntityRep.find({
      where: {
        delFlag: DelFlagEnum.NORMAL,
        status: StatusEnum.NORMAL,
        menuId: In(menuIds)
      }
    })
    // 构建前端需要的菜单树
    const menuTree = buildMenus(menuList)
    return menuTree
  }
}
